package com.wpml.product.controller.test;

import cn.hutool.core.lang.UUID;
import org.redisson.api.RLock;
import org.redisson.api.RReadWriteLock;
import org.redisson.api.RedissonClient;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.TimeUnit;

/**
 * @description:
 * @author: wp
 * @date: 2020/6/29
 **/
@RestController
public class RedissonTestController {

    @Resource
    private RedissonClient redisson;

    static ConcurrentHashMap<String, String> hashMap = new ConcurrentHashMap<>();
    static {
        hashMap.put("writeValue", "test readWriteLock");
    }


    @GetMapping("/helloRedisson")
    public String helloRedisson() {

        RLock lock = redisson.getLock("testRedisson");
        lock.lock(); // 阻塞式等待
        // 未指定超时时间 锁自动续期，默认超时时间30秒，看门狗机制，业务运行期间自动续期（每10秒执行一次）
        try {
            System.out.println("获取锁，执行业务逻辑。。。" + Thread.currentThread().getId());
            try {
                TimeUnit.SECONDS.sleep(20);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        } finally {
            System.out.println("释放锁。。。" + Thread.currentThread().getId());
            lock.unlock();
        }

        return "helloRedisson";
    }

    /**
     * @description: 读写锁实现案例
     * 写锁是一个排他锁（互斥锁），读锁是共享锁
     * @author: wang pei
     * @date: 2020/6/30 10:02
     **/
    @GetMapping("/write")
    public String writeValue() {
        RReadWriteLock readWriteLock = redisson.getReadWriteLock("rw-lock");
        RLock rLock = readWriteLock.writeLock();
        rLock.lock();
        System.out.println("获取写锁。。。");
        String value = UUID.fastUUID().toString(true);
        try {
            hashMap.put("writeValue", value);
            TimeUnit.SECONDS.sleep(20);
        } catch (InterruptedException e) {
            e.printStackTrace();
        } finally {
            rLock.unlock();
        }

        return value;
    }


    @GetMapping("/read")
    public String readValue() {
        RReadWriteLock readWriteLock = redisson.getReadWriteLock("rw-lock");
        RLock rLock = readWriteLock.readLock();
        rLock.lock();
        System.out.println("获取读锁。。。");
        String value;
        try {
            value = hashMap.get("writeValue");
        } finally {
            rLock.unlock();
        }

        return value;
    }

    @GetMapping("/testSynchronized")
    public void testSynchronized() {
        synchronized (this) {

            System.out.println("11111111");

            try {
                TimeUnit.SECONDS.sleep(10);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }
}
